import { createRouter, createWebHashHistory } from "vue-router";
import { routes } from "./route.list";
import { storage } from "../middleware";
import { mainStore } from "/@/store/index";
import eventBus from "../eventBus";

/**
 * 路由
 */
export const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});

/**
 * 路由守卫
 */
router.beforeEach((to, _, next) => {
  const store = mainStore();
  const token = storage?.get("token");

  if (token) {
    if (store.menu.length === 0) {
      store.getMenu();
    }
    if (to.path === "/login") {
      storage?.clear();
      next();
    } else {
      if (to.matched.length === 0) {
        next({ path: "/404" });
      } else {
        next();
      }
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});

/**
 * 路由监听
 */
eventBus.on("loginSuccess", () => router.push("/user"));
eventBus.on("logout", () => {
  router.push("/login");
  storage?.clear();
});
